<template>
  <a-card class="profile-container">
    <div class="header">
      <h2 class="title">个人信息管理</h2>
      <div class="divider"></div>
    </div>

    <a-spin :spinning="loading">
      <a-form :model="formState" layout="vertical" class="form-container">
        <!-- 头像上传 -->
        <a-form-item label="我的头像" class="form-item">
          <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
            :before-upload="beforeUpload">
            <div class="avatar-container">
              <img v-if="formState.coverUrl" :src="formState.coverUrl" class="avatar" />
              <div class="upload-mask">
                <plus-outlined class="upload-icon" />
                <div class="ant-upload-text">更换头像</div>
              </div>
            </div>
          </a-upload>
          <div class="upload-tips">建议尺寸 200x200px，支持 JPG/PNG 格式</div>
        </a-form-item>

        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <div class="form-grid">
            <a-form-item label="姓名" name="title" :rules="[{ required: true, message: '请输入姓名' }]" class="form-item">
              <a-input v-model:value="formState.title" placeholder="请输入您的姓名" allow-clear />
            </a-form-item>

            <a-form-item label="性别" name="sex" :rules="[{ required: true, message: '请选择性别' }]" class="form-item">
              <a-select v-model:value="formState.sex" placeholder="请选择性别" :options="[
                { value: '男', label: '男' },
                { value: '女', label: '女' },
              ]" />
            </a-form-item>

            <a-form-item label="年龄" name="age" :rules="[{ required: true, message: '请输入年龄' }]" class="form-item">
              <a-input-number v-model:value="formState.age" :min="18" :max="60" class="full-width" />
            </a-form-item>

            <a-form-item label="地区" name="location" :rules="[{ required: true, message: '请输入地区' }]" class="form-item">
              <a-cascader v-model:value="formState.location" :options="regionData" placeholder="请选择地区"
                :field-names="{ label: 'label', value: 'value', children: 'children' }" />
            </a-form-item>

            <a-form-item label="辅导阶段" name="classificationId" :rules="[{ required: true, message: '请选择辅导阶段' }]"
              class="form-item">
              <a-select v-model:value="formState.classificationId" placeholder="请选择年级" :options="classificationOptions"
                :field-names="{ label: 'title', value: 'id' }" />
            </a-form-item>


            <a-form-item label="辅导科目" name="tags" :rules="[{ required: true, message: '请选择辅导科目' }]" class="form-item">
              <a-select v-model:value="formState.tags" placeholder="请选择科目" :options="tagOptions"
                :field-names="{ label: 'title', value: 'id' }" />
            </a-form-item>

          </div>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h3 class="section-title">联系信息</h3>
          <div class="form-grid">
            <a-form-item label="手机号" name="mobile" :rules="[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
            ]" class="form-item">
              <a-input v-model:value="formState.mobile" placeholder="请输入手机号码" allow-clear />
            </a-form-item>

            <a-form-item label="授课价格" name="price" :rules="[{ required: true, message: '请输入授课价格' }]" class="form-item">
              <a-input-number v-model:value="formState.price" :min="0" :precision="0" addon-after="元/小时"
                class="full-width" />
            </a-form-item>
          </div>
        </div>



        <!-- 详细信息 -->
        <div class="form-section">
          <h3 class="section-title">详细信息</h3>
          <a-form-item label="个人简介" name="description" :rules="[{ required: true, message: '请输入个人简介' }]"
            class="form-item">
            <a-textarea v-model:value="formState.description" placeholder="请输入您的教学经历、获奖情况等" :rows="4" :maxlength="200"
              show-count />
          </a-form-item>
        </div>

        <div class="form-actions">
          <a-button type="primary" size="large" @click="handleSubmit" :loading="submitting">
            <template #icon><save-outlined /></template>
            {{ submitting ? '保存中...' : '保存更改' }}
          </a-button>
        </div>
      </a-form>
    </a-spin>
  </a-card>
</template>


<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SaveOutlined,
  PlusOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '/@/store'
import { get, post } from '/@/utils/http/axios'
import { BASE_URL } from '/@/store/constants'
import regionData from '/@/utils/region'
import { getClassificationList, getTagList } from '/@/api/thing'

const userStore = useUserStore()
const loading = ref(false)
const uploadLoading = ref(false)
const submitting = ref(false)
const classificationOptions = ref<{ id: number; title: string }[]>([])
const tagOptions = ref<{ id: number; title: string }[]>([])

const formState = reactive({
  id: undefined,
  title: '',
  sex: undefined,
  age: undefined,
  location: [],
  mobile: '',
  price: undefined,
  description: '',
  coverUrl: '',
  imageFile: null as File | null,
  classificationId: undefined as number | undefined,
  tags: [] as number[],
})

// 获取教师信息
const fetchTeacherInfo = async () => {
  try {
    loading.value = true
    const res = await get({
      url: '/api/thing/getUserThingByUserId',
      params: { userId: userStore.user_id }
    })

    if (res.data) {
      Object.assign(formState, {
        id: res.data.id,
        title: res.data.title,
        sex: res.data.sex,
        age: res.data.age,
        location: res.data.location ? res.data.location.split('-') : [],
        mobile: res.data.mobile,
        price: res.data.price,
        description: res.data.description,
        classificationId: res.data.classificationId,
        tags: res.data.tags || [],
        coverUrl: res.data.cover
          ? `${BASE_URL}/api/staticfiles/image/${res.data.cover}`
          : ''
      })
    }
  } catch (error) {
    message.error('获取教师信息失败')
  } finally {
    loading.value = false
  }
}

// 头像上传处理
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt4M = file.size / 1024 / 1024 < 4
  if (!isLt4M) {
    message.error('图片大小不能超过4MB!')
    return false
  }

  // 预览图片
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    formState.coverUrl = reader.result as string
  }

  formState.imageFile = file
  return false // 阻止自动上传
}

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true

    const formData = new FormData()
    if (formState.imageFile) {
      formData.append('imageFile', formState.imageFile)
    }

    // 添加其他字段
    const fields = {
      id: formState.id,
      title: formState.title,
      sex: formState.sex,
      age: formState.age,
      location: formState.location.join('-'),
      mobile: formState.mobile,
      price: formState.price,
      description: formState.description,
      userId: userStore.user_id,
      classificationId: formState.classificationId,
      tags: Array.isArray(formState.tags) ? formState.tags : [formState.tags]
    }

    Object.entries(fields).forEach(([key, value]) => {
      if (value !== undefined) {
        // 处理数组类型字段
        if (key === 'tags') {
          formData.append(key, JSON.stringify(value))
        } else {
          formData.append(key, value.toString())
        }
      }
    })

    const apiUrl = formState.id ? '/api/thing/updateUserThing' : '/api/thing/create'
    const res = await post({
      url: apiUrl,
      data: formData,
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (res.code === 200) {
      message.success(formState.id ? '信息更新成功' : '信息创建成功')
      await fetchTeacherInfo() // 刷新数据
    }
  } catch (error) {
    message.error('操作失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 获取分类和标签数据
const fetchOptionsData = async () => {
  try {
    const [classRes, tagRes] = await Promise.all([
      getClassificationList(),
      getTagList()
    ])

    classificationOptions.value = classRes.data.map((item: any) => ({
      id: item.id,
      title: item.title
    }))

    tagOptions.value = tagRes.data.map((item: any) => ({
      id: item.id,
      title: item.title
    }))
  } catch (error) {
    message.error('获取选项数据失败')
  }
}



onMounted(() => {
  fetchTeacherInfo()
  fetchOptionsData()
})



</script>

<style scoped lang="less">
.profile-container {
  max-width: 1200px;
  margin: 24px auto;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .header {
    margin-bottom: 32px;

    .title {
      font-size: 24px;
      color: #1a3353;
      margin: 0;
    }

    .divider {
      height: 2px;
      background: linear-gradient(90deg, #6a8bad 0%, #a2b9d6 100%);
      margin-top: 16px;
    }
  }
}

.form-container {
  padding: 0 24px;

  .form-section {
    margin-bottom: 32px;
    padding: 24px;
    background: #f8fafc;
    border-radius: 8px;

    .section-title {
      color: #2c3e50;
      font-size: 18px;
      margin-bottom: 24px;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: #4684e2;
        border-radius: 2px;
      }
    }
  }
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.avatar-uploader {
  :deep(.ant-upload) {
    width: 128px;
    height: 128px;
    border-radius: 50%;
    overflow: hidden;
    background: #f0f2f5;
    position: relative;

    .avatar-container {
      position: relative;
      width: 100%;
      height: 100%;
    }

    .upload-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.4);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      .upload-icon,
      .ant-upload-text {
        color: #fff;
      }
    }

    &:hover .upload-mask {
      opacity: 1;
    }

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

.form-actions {
  text-align: center;
  margin-top: 40px;

  .ant-btn {
    padding: 0 40px;
    height: 42px;
    font-size: 16px;
    border-radius: 8px;
  }
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .profile-container {
    margin: 12px;
  }
}

.ant-cascader-picker {
  width: 100%;

  .ant-input {
    height: 40px;
    border-radius: 4px;

    &::placeholder {
      color: #a8abb2;
    }
  }
}

.ant-cascader-menus {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;

  .ant-cascader-menu {
    min-width: 120px;

    &:not(:last-child) {
      border-right: 1px solid #f0f2f5;
    }
  }
}

.ant-select {
  width: 100%;
}
</style>